package cn.wolfcode.mq;

import cn.wolfcode.ws.WebsocketServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_RESULT_TOPIC,
        consumerGroup = MQConstant.ORDER_RESULT_TOPIC + "_CUSTOMER_GROUP"
)
public class MQOrderResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        try {
            // 防止处理太快, websocket还没建立连接, 先睡1秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println("订单结果通知成功=================================");
        WebsocketServer websocketServer = WebsocketServer.websocketServerMap.get(orderMQResult.getToken());
        if (websocketServer != null) {
            try {
                websocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            // 订单结果通知失败
            System.out.println("订单结果通知失败");
        }
    }
}
